﻿using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.NoNet;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System.Collections.Generic;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.出库管理
{
    /// <summary>
    /// 出库
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TShippingOrderDetailController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        private readonly SqliteContext sqliteContext;
        private readonly ITInventoryRepository tInventory;
        private readonly ITShippingLockCellRepository tShippingLockCell;
        private readonly ITWarehouseRepository tWarehouse;

        public ITShippingOrderDetailRepository _service { get; set; }

        public TShippingOrderDetailController(
            ITShippingOrderDetailRepository service,
            ITInventoryRepository tInventory,
            ITShippingLockCellRepository tShippingLockCell,
            ITWarehouseRepository tWarehouse,
            ILogRepository logRepository,
            SqliteContext sqliteContext
            )
        {
            _service = service;
            this.logRepository = logRepository;
            this.sqliteContext = sqliteContext;
            this.tInventory = tInventory;
            this.tShippingLockCell = tShippingLockCell;
            this.tWarehouse = tWarehouse;
        }

        /// <summary>
        /// 添加出库表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddTShippingOrderDetail")]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddTShippingOrderDetail(GroupShippingOrderDto model)
        {
            var create = _service.AddTShippingOrderDetail(model,out string message);
            if (create)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "入库管理";
                logg.UserName = uname;
                logg.RealName = runame;                                 
                logg.UserId = uid;
                logg.Description = uname + "创建了入库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /*
        /// <summary>
        /// 添加出库表 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("AddTShippingOrderDetailPlus")]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult AddTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            var create = _service.AddTShippingOrderDetailPlus(model,out var msg);
            if (create)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 4;
                logg.ModuleName = "入库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "创建了入库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, msg, "500"));
        }

        */
        /// <summary>
        /// 删除出库单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteTShippingOrderDetail")]
        public IActionResult DeleteTShippingOrderDetail(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = _service.DeleteTShippingOrderDetail(id);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }


        /// <summary>
        /// 删除出库单  多个物料单版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("DeleteTShippingOrderDetailPlus")]
        public IActionResult DeleteTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            if (model == null)
            {
                return Ok(BaseResult.Result("400", "请求参数有误！"));
            }
            bool IsOK = _service.DeleteTShippingOrderDetailPlus(model);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！", "500"));
        }


        /// <summary>
        /// 修改出库表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("UpdateTShippingOrderDetail")]
        public IActionResult UpdateTShippingOrderDetail(TShippingOrderDetail model)
        {
            if(model.Id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var update = _service.UpdateTShippingOrderDetail(model);
            if (update)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "出库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了入库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }



        /// <summary>
        /// 修改出库表 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut("UpdateTShippingOrderDetailPlus")]
        public IActionResult UpdateTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            //if (model.Id <= 0)
            //{
            //    return Ok(BaseResult.Result("400", "Id有误！"));
            //}
            var update = _service.UpdateTshippingOrderDetailPlus(model);
            if (update)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "出库管理";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了出库单" + model.OrderSn;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }

        /// <summary>
        /// 显示出库表
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetAllTShippingOrderDetail")]
        public IActionResult GetAllTShippingOrderDetail(int? billType, int? houseid, string? name, int pageIndex = 1, int pageSize = 8)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = _service.GetAllTShippingOrderDetail(billType, houseid, name, pageIndex, pageSize, out totalCount);
            if (list.Count >= 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// 显示出库表
        /// </summary>
        /// <param name="billType"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetAllTShippingOrderDetailPlus")]
        public IActionResult GetAllTShippingOrderDetailPlus(int? billType, int? houseid, string? name, int pageIndex = 1, int pageSize = 8)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = _service.GetAllTShippingOrderDetailPlus(billType, houseid, name, pageIndex, pageSize, out totalCount);
            if (list.Count >= 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("GetTShippingOrderDetailById")]
        public IActionResult GetTShippingOrderDetailById(int id)
        {
            if(id<=0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }

            var orderDetail = _service.GetByIdTShippingOrderDetail(id);
            if (orderDetail != null)
            {
                return Ok(BaseResult.Result(orderDetail, "查询成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "未找到该出库表！", "404"));
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut("UpdTShippingOrderDetailState")]
        public IActionResult UpdTShippingOrderDetailState(ReceivingOrderDetailDto m)
        {
            bool IsOK = _service.UpdTShippingOrderDetailState(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功！", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败！输入的工号有误！", "500"));
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult SelectTShippingOrderDetail(TShippingOrderDetail model)
        {
            var success = SelectTShippingOrderDetail(model);
            if (success != null)
            {
                return Ok(new { success = true, message = "选定成功", code = "200" });
            }
            else
            {
                return Ok(new { success = false, message = "选定失败,是否物料名称，库房，批次号，出库数量已选", code = "500" });
            }
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        //[HttpPost("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(TShippingOrderDetail model)
        //{
        //    try
        //    {
        //        List<TShippingLockCell> selectedCells = new List<TShippingLockCell>();

        //        // 校验物料Id是否为空或无效
        //        if (model.MaterialId <= 0)
        //        {
        //            return BadRequest("请选择物料");
        //        }

        //        // 校验数量是否为空或无效
        //        if (model.Qty <= 0)
        //        {
        //            return BadRequest("请选择出库数量");
        //        }

        //        // 校验仓库Id是否为空或无效
        //        if (model.WarehouseId <= 0)
        //        {
        //            return BadRequest("请选择仓库");
        //        }

        //        selectedCells = _service.GetAllTShippingLockCell(model)
        //            .Where(cell =>
        //                cell.InventoryQty >= model.Qty && cell.WhId == model.WarehouseId &&
        //                cell.MaterialId == model.MaterialId)
        //            .ToList();

        //        return Ok(selectedCells);
        //    }
        //    catch (Exception ex)
        //    {
        //        return StatusCode(500, $"发生错误: {ex.Message}");
        //    }
        //}

        /// <summary>
        /// 根据物料Id返回批次和数量(之前)
        /// 现：根据选择的物料返回可选择的批次号下拉框
        /// 
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="warehouseCode">库房编码</param>
        /// <param name="areaCode">库区编码</param>
        /// <param name="materialId">物料id</param>
        /// <param name="batchNO">批次号</param>
        /// <param name="qualityState">质量状态</param>
        /// <param name="expectedQTY">预计出库数量</param>
        /// <param name="ownerId">货主id</param>
        /// <param name="lockCellList">out 分配到的仓位</param>
        /// <param name="errorMsg">错误信息</param>
        /// <param name="orderDetailId">出库单详细Id</param>
        /// <param name="supplierId">供应商id</param>
        /// <param name="produceFactory">生产厂家</param>
        /// <returns></returns>
        [HttpGet("GetMaterialIdById")]
        public IActionResult GetMaterialIdById(int materialId, string? batchNO, int? qualityState, string? whCode, string? areaCode, string? produceFactory, int? ownerId, int? supplierId = null)
        {
            if (materialId <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var mobj = _service.GetMaterialIdById(materialId, batchNO,qualityState, whCode,areaCode,ownerId,supplierId,produceFactory);
            if (mobj != null)
            {
                return Ok(BaseResult.Result(mobj, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 一键选定 弃用
        /// </summary>
        /// <param name="materid"></param>
        /// <param name="count"></param>
        /// <param name="whid"></param>
        /// <param name="areaid"></param>
        /// <param name="supid"></param>
        /// <param name="owid"></param>
        /// <returns></returns>
        //[HttpGet("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(int materid = 0, int count = 0, int whid = 0, int areaid = 0, int supid = 0, int owid = 0)
        //{
        //    if (materid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "物料有误！"));
        //    }
        //    if (count <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "请选择出库数量！"));
        //    }
        //    if (whid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "库房有误！"));
        //    }
        //    if (areaid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "库区有误！"));
        //    }
        //    if (supid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "供应商有误！"));
        //    }
        //    if (owid <= 0)
        //    {
        //        return Ok(BaseResult.Result("400", "货主有误！"));
        //    }
        //    var list = _service.GetAllTShippingLockCell(materid, count, whid, areaid, supid, owid);
        //    if (list != null)
        //    {
        //        return Ok(BaseResult.Result(list, "查询成功！", "200", 0));
        //    }

        //    return Ok(BaseResult.Result("200", "库存数量不足1，部分库存可能已被其它出库单锁定"));
        //}
        /// <summary>
        /// 一键选定 弃用
        /// </summary>
        /// <param name="materid"></param>
        /// <param name="count"></param>
        /// <param name="whid"></param>
        /// <param name="areaid"></param>
        /// <param name="supid"></param>
        /// <param name="owid"></param>
        /// <returns></returns>
        //[HttpGet("GetAllTShippingLockCell")]
        //public IActionResult GetAllTShippingLockCell(string? batchNO, int MaterialId, decimal Qty, string whCode, int? qualityState, string? areaCode, int? SupplierId, int? OwnerId, int? orderDetailId = null, string? produceFactory = "")
        //{


        //    //_service.GetAllTShippingLockCell(materid, count, whid, areaid, supid, owid);
        //    var res = tShippingLockCell.LockCell(whCode, areaCode, MaterialId, batchNO, qualityState, Qty, OwnerId, out var lockCellList, out var errorMsg, orderDetailId, SupplierId, produceFactory);
        //    if (res)
        //        return Ok(BaseResult.Result(lockCellList, "查询成功！", "200"));
        //    return Ok(BaseResult.Result(false, errorMsg, "500"));
        //}

        /// <summary>
        /// 获取货品明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetOneTShippingGoods")]
        public IActionResult GetOneTShippingGoods(int id, int pageIndex = 1, int pageSize = 8)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var goodsDetail = _service.GetOneTShippingGoodsDetail(id, pageIndex, pageSize, out totalCount);
            if (goodsDetail != null)
            {
                return Ok(BaseResult.Result(goodsDetail, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 根据名字获取
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetByNameShippingGoodsDetail")]
        public IActionResult GetByNameShippingGoodsDetail(string? name, int pageIndex = 1, int pageSize = 8)
        {
            if(pageIndex<=0 || pageSize<=0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var goodsDetail = _service.GetByNameShippingGoodsDetail(name, pageIndex, pageSize, out totalCount);
            if (goodsDetail != null && goodsDetail.Any())
            {
                return Ok(BaseResult.Result(goodsDetail, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }
        /// <summary>
        /// fghj
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTest")]
        public IActionResult GetTest()
        {
            for (int i = 0; i < 100000; i++)
            {
                //插入数据
                var data = new Dfgk { Code = "zh"+i , Name = "子涵"+i };
                sqliteContext.Dfgk.Add(data);
                sqliteContext.SaveChanges();
            }



            return Ok(sqliteContext.Dfgk);
        }
    }
}